package org.fuxia.im.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

import org.fuxia.im.common.ClientConst;
import org.fuxia.im.common.ClientContext;
import org.fuxia.im.common.IconManager;
import org.fuxia.im.core.ECMessageType;
import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.iconst.Constant;
import org.fuxia.im.core.socket.impl.ECNioClient;
import org.fuxia.im.gui.util.FileUtil;
import org.fuxia.im.listeners.AddUserFriendsListener;
import org.fuxia.im.listeners.AddUserGroupListener;
import org.fuxia.im.listeners.CommonListener;
import org.fuxia.im.listeners.DelUserListener;
import org.fuxia.im.listeners.FileTransferListener;
import org.fuxia.im.listeners.GroupAddResultListener;
import org.fuxia.im.listeners.GroupOptionListener;
import org.fuxia.im.listeners.HandlerAddGroupApplyListener;
import org.fuxia.im.listeners.LoginResponseListener;
import org.fuxia.im.listeners.MoveFriendListener;
import org.fuxia.im.listeners.QueryResultListener;
import org.fuxia.im.listeners.ReceiveAddedListener;
import org.fuxia.im.listeners.ReceiveMessageListener;
import org.tony.common.ui.CommonFrame;

public class Login extends CommonFrame{

	private static final long	serialVersionUID	= 1L;
	
	private JPanel				contentPane;
	private JTextField			userNameField;
	private JPasswordField		passwordField;
	private JCheckBox chckbxNewCheckBox ;

	/**
	 * Launch the application.
	 * @throws UnsupportedLookAndFeelException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws ClassNotFoundException
	 */
	public static void main(String[] args) 
	{
		try {
			UIManager.setLookAndFeel("org.jvnet.substance.skin.SubstanceCremeLookAndFeel");
		} catch (Exception e) {
		}
		//UIManager.setLookAndFeel("org.jvnet.substance.skin.SubstanceOfficeBlue2007LookAndFeel");
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ClientContext.getContext();
					Login frame = new Login();
					ClientContext.putValue(ClientConst.LOGIN_WINDOW, frame);
					frame.setVisible(true);
					IconManager.lazyInit() ;
					UIManager.put("Tree.leftChildIndent", -12);
					UIManager.put("Tree.openIcon", IconManager.getIcon("unfold.jpg")) ;
					UIManager.put("Tree.closedIcon", IconManager.getIcon("fold.jpg")) ;
					UIManager.put("Menu.selectionForeground", new Color(0,0,0));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		SwingUtilities.invokeLater(new Runnable() {
			public void run()
			{
				try
				{

					FileTransferListener ftl = new FileTransferListener() ;
					ECNioClient client = new ECNioClient(ClientContext
							.getContext().get("host").toString(), 8989);
					client.registPacketListener(new ReceiveMessageListener(),
							"PLAINMESSAGE");
					
					QueryResultListener qrl = new QueryResultListener() ;
					client.registResponseListener(new GroupOptionListener(), "GROUP_OPTION") ;
					client.registResponseListener(new GroupAddResultListener(), "GROUP_ADD_RESULT");
					client.registResponseListener(new LoginResponseListener(), "LOGIN_RESP");
					client.registResponseListener(new CommonListener(), "RESPONSE");
					client.registResponseListener(qrl, "query_result");
					client.registResponseListener(qrl, "QUERY_GROUP_RESP");
					client.registResponseListener(new AddUserFriendsListener(), "ADD_FRIEND") ;
					client.registPacketListener(ftl, "FILE_TRANSFER_INFO");
					client.registPacketListener(ftl, "CANCEL_FILE_TRANSFER");
					client.registPacketListener(ftl, "FILE_TRANSFER_ACK");
					client.registPacketListener(new HandlerAddGroupApplyListener(), "ADD_GROUP") ;
					client.registPacketListener(new ReceiveAddedListener(), "receiveAdd") ;
					client.registResponseListener(new AddUserGroupListener(), "addUserGroup") ;
					client.registResponseListener(new MoveFriendListener(), "moveFriend") ;
					client.registResponseListener(new DelUserListener(), "DEL_USER") ;
					
					new Thread(client).start();
					ClientContext.getContext().setClient(client);
					ClientContext.putValue(ClientConst.MESSAGE_QUEUE,
							new ConcurrentHashMap<String, String>());
				}
				catch (IOException e1)
				{
					JOptionPane.showMessageDialog(null, "连接服务器失败");
				}
			}
		});

	}

	/**
	 * Create the frame.
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Login()
	{
		super();
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 403, 326);
		setTitle("即时聊天");
		
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContent(contentPane);

		JPanel panel = new JPanel();
		panel.setOpaque(false);
		contentPane.add(panel, BorderLayout.CENTER);
		panel.setLayout(null);

		JLabel lblNewLabel = new JLabel("");
		lblNewLabel.setIcon(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("images/default.jpg"))) ;
		lblNewLabel.setBounds(39, 116, 60, 60);
		panel.add(lblNewLabel);

		userNameField = new JTextField();
		userNameField.setBounds(121, 116, 179, 26);
		panel.add(userNameField);
		userNameField.setColumns(10);

		JButton btnNewButton = new JButton("登录");
		btnNewButton.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		btnNewButton.setBounds(128, 242, 70, 26);
		panel.add(btnNewButton);
		btnNewButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				SwingUtilities.invokeLater(new Runnable() {

					public void run()
					{

						String userName = userNameField.getText().trim();
						String password = new String(passwordField.getPassword());
						if (userName == null || userName.length() == 0)
						{
							JOptionPane.showMessageDialog(getPannel(),
									"用户名必须输入", "错误", JOptionPane.ERROR_MESSAGE);
							return;
						}
						if (password == null || password.length() == 0)
						{
							JOptionPane.showMessageDialog(getPannel(),
									"密码必须输入", "错误", JOptionPane.ERROR_MESSAGE);
							return;
						}
						setVisible(false);
						ECNioClient c = ClientContext.getContext().getClient();
						ECPacket packet = new ECPacket();
						packet.setMessageType(ECMessageType.LOGIN.name());
						packet.setFrom(userName) ;
						packet.addParam(Constant.USERCODE.name(), userName);
						packet.addParam(Constant.PASSWORD.name(), password);
						ClientContext.putValue("REMEMBER_USER", chckbxNewCheckBox.isSelected());
						ClientContext.putValue("PASS", password);
						try
						{
							c.sendMessage(packet);
						}
						catch (Exception e)
						{
							JOptionPane.showMessageDialog(getPannel(),
									"网络连接失败", "错误", JOptionPane.ERROR_MESSAGE);
						}
						Logining l = new Logining();
						ClientContext.putValue(ClientConst.LOGING_WINDOW, l);
						l.setVisible(true);
					}
				});
			}
		});

		JButton button = new JButton("\u6CE8\u518C");
		button.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		button.setBounds(209, 242, 70, 26);
		panel.add(button);
		button.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e)
			{
				SwingUtilities.invokeLater(new Runnable() {

					public void run()
					{
						Regist regWindow = new Regist();
						ClientContext.putValue(ClientConst.REG_WINDOW,
								regWindow);
						regWindow.setVisible(true);
					}
				});
			}
		});

		passwordField = new JPasswordField();
		passwordField.setBounds(121, 152, 179, 26);
		panel.add(passwordField);

		chckbxNewCheckBox = new JCheckBox("\u8BB0\u4F4F\u5BC6\u7801");
		chckbxNewCheckBox.setOpaque(false);
		chckbxNewCheckBox.setBorder(null);
		chckbxNewCheckBox.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		chckbxNewCheckBox.setBounds(185, 194, 90, 15);
		panel.add(chckbxNewCheckBox);

		JComboBox comboBox = new JComboBox();
		comboBox.setOpaque(false);
		comboBox.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		comboBox.setModel(new DefaultComboBoxModel(new String[] { "\u9690\u8EAB", "\u4E0A\u7EBF", "Q\u6211\u5427" }));
		comboBox.setBounds(121, 188, 58, 21);
		panel.add(comboBox);
		
		Map<String, String> info = FileUtil.readRecord(ClientContext.getValue("sys-data-file", String.class)) ;
		if(info!=null && info.size()>0) {
			Iterator<String> iter = info.keySet().iterator();
			if(iter.hasNext()) {
				String key = iter.next() ;
				String value = info.get(key);
				userNameField.setText(key);
				passwordField.setText(value);
				chckbxNewCheckBox.setSelected(true);
			}
		}
	}

	public JPanel getPannel()
	{
		return this.contentPane;
	}

}
